<template>
  <div class="workflow-detail">
    <div class="header">
      <h2>{{ isEdit ? '编辑工作流' : '创建工作流' }}</h2>
      <div class="actions">
        <el-button @click="$router.back()">返回</el-button>
        <el-button 
          type="primary" 
          @click="saveAndNext" 
          :loading="saving"
        >
          下一步
        </el-button>
        <el-button 
          @click="saveWorkflow" 
          :loading="saving"
        >
          保存
        </el-button>
      </div>
    </div>

    <el-form 
      ref="formRef"
      :model="workflowForm"
      :rules="rules"
      label-width="120px"
      class="workflow-form"
    >
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>

        <el-form-item label="名称" prop="name">
          <el-input v-model="workflowForm.name" placeholder="请输入工作流名称" />
        </el-form-item>

        <el-form-item label="功能描述" prop="description">
          <el-input
            v-model="workflowForm.description"
            type="textarea"
            :rows="3"
            placeholder="请描述此工作流的主要功能和使用场景"
          />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input 
            v-model="workflowForm.author" 
            placeholder="请输入作者名称"
          />
        </el-form-item>

        <el-form-item label="模型类型" prop="model_type">
          <el-select 
            v-model="workflowForm.model_type" 
            placeholder="请选择模型类型"
          >
            <el-option label="Stable Diffusion" value="sd" />
            <el-option label="Midjourney" value="mj" />
            <el-option label="DALL-E" value="dalle" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select v-model="workflowForm.category" placeholder="请选择分类">
            <el-option label="文生图" value="text2img" />
            <el-option label="图生图" value="img2img" />
            <el-option label="人物肖像" value="portrait" />
          </el-select>
        </el-form-item>

        <el-form-item label="预览图" prop="preview_image">
          <el-upload
            class="avatar-uploader"
            action="/api/v1/upload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :headers="uploadHeaders"
          >
            <img 
              v-if="workflowForm.preview_image" 
              :src="workflowForm.preview_image" 
              class="avatar" 
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-card>

      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>工作流配置</span>
            <el-button 
              type="primary" 
              size="small"
              @click="importWorkflowClick"
            >
              导入工作流
            </el-button>
          </div>
        </template>

        <el-form-item label="参数配置" prop="param_schema">
          <el-input
            v-model="paramSchemaStr"
            type="textarea"
            :rows="10"
            placeholder="请输入参数配置 JSON"
            @input="validateParamSchema"
          />
        </el-form-item>

        <el-form-item label="工作流配置" prop="workflow_json">
          <el-input
            v-model="workflowJsonStr"
            type="textarea"
            :rows="15"
            :disabled="true"
            placeholder="请导入 ComfyUI 工作流 JSON"
          />
        </el-form-item>

        <!-- 添加隐藏的文件输入框 -->
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          accept=".json"
          @change="handleFileImport"
        />
      </el-card>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { request } from '@/utils/request'

const route = useRoute()
const router = useRouter()
const formRef = ref()
const saving = ref(false)

const isEdit = computed(() => !!route.params.id)

const workflowForm = ref({
  name: '',
  description: '',
  author: '',
  model_type: '',
  category: '',
  preview_image: '',
  param_schema: {},
  workflow_json: {}
})

const fileInput = ref<HTMLInputElement | null>(null)
const workflowJsonStr = computed(() => {
  return JSON.stringify(workflowForm.value.workflow_json, null, 2)
})

// 将对象转换为格式化的字符串
const paramSchemaStr = computed({
  get: () => JSON.stringify(workflowForm.value.param_schema, null, 2),
  set: (val) => {
    try {
      workflowForm.value.param_schema = JSON.parse(val)
    } catch (e) {
      // 解析失败时不更新值
    }
  }
})

const rules = {
  name: [
    { required: true, message: '请输入工作流名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入功能描述', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者名称', trigger: 'blur' }
  ],
  model_type: [
    { required: true, message: '请选择模型类型', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 验证 JSON 格式
const validateJson = (str: string): boolean => {
  try {
    JSON.parse(str)
    return true
  } catch (e) {
    return false
  }
}

const validateParamSchema = (val: string) => {
  if (!validateJson(val)) {
    ElMessage.warning('参数配置 JSON 格式无效')
  }
}

const validateWorkflowJson = (val: string) => {
  if (!validateJson(val)) {
    ElMessage.warning('工作流配置 JSON 格式无效')
  }
}

// 获取工作流详情
const fetchWorkflowDetail = async (id: string) => {
  try {
    const data = await request(`/api/v1/workflows/${id}`)
    workflowForm.value = {
      ...data,
      param_schema: data.param_schema || {},
      workflow_json: data.workflow_json || {}
    }
  } catch (error) {
    console.error('获取工作流详情失败:', error)
    ElMessage.error('获取工作流详情失败：' + (error instanceof Error ? error.message : '未知错误'))
  }
}

// 上传相关方法
const uploadHeaders = {
  // 如果需要认证token等，可以在这里添加
}

const handleUploadSuccess = (response: any) => {
  if (response?.url) {
    workflowForm.value.preview_image = response.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败：未获取到文件URL')
  }
}

const handleUploadError = (error: any) => {
  console.error('上传失败:', error)
  // 解析错误信息
  let errorMessage = '图片上传失败'
  try {
    if (error.response) {
      const response = JSON.parse(error.response)
      errorMessage = response.message || errorMessage
    }
  } catch (e) {
    // 如果解析失败，使用默认错误信息
  }
  ElMessage.error(errorMessage)
}

const beforeUpload = (file: File) => {
  // 修改文件类型验证
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg']
  const isImage = allowedTypes.includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传 JPG/JPEG/PNG/GIF 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 保存并进入通用模板
const saveAndNext = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }

  saving.value = true
  try {
    const url = isEdit.value 
      ? `/api/v1/workflows/${route.params.id}`
      : '/api/v1/workflows'
    
    const response = await request(url, {
      method: isEdit.value ? 'PUT' : 'POST',
      body: JSON.stringify({
        name: workflowForm.value.name,
        description: workflowForm.value.description,
        author: workflowForm.value.author,
        model_type: workflowForm.value.model_type,
        category: workflowForm.value.category,
        preview_image: workflowForm.value.preview_image,
        param_schema: workflowForm.value.param_schema || {},
        workflow_json: workflowForm.value.workflow_json || {}
      })
    })
    
    ElMessage.success('保存成功')
    
    // 根据分类跳转到对应的通用模板
    const templateRoutes: Record<string, string> = {
      'text2img': '/templates/text2img',
      'img2img': '/templates/img2img',
      'portrait': '/templates/portrait'
    }
    
    const nextRoute = templateRoutes[workflowForm.value.category]
    if (nextRoute) {
      router.push({
        path: nextRoute,
        query: { 
          workflow_id: isEdit.value ? route.params.id : response.id,
          mode: 'edit'
        }
      })
    } else {
      ElMessage.warning('未找到对应的模板页面')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败：' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    saving.value = false
  }
}

// 保存工作流
const saveWorkflow = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }

  saving.value = true
  try {
    const url = isEdit.value 
      ? `/api/v1/workflows/${route.params.id}`
      : '/api/v1/workflows'
    
    const method = isEdit.value ? 'PUT' : 'POST'
    
    await request(url, {
      method,
      body: JSON.stringify({
        name: workflowForm.value.name,
        description: workflowForm.value.description,
        author: workflowForm.value.author,
        model_type: workflowForm.value.model_type,
        category: workflowForm.value.category,
        preview_image: workflowForm.value.preview_image,
        param_schema: workflowForm.value.param_schema || {},
        workflow_json: workflowForm.value.workflow_json || {}
      })
    })
    
    ElMessage.success('保存成功')
    router.push('/workflows')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败：' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    saving.value = false
  }
}

// 点击导入按钮
const importWorkflowClick = () => {
  fileInput.value?.click()
}

// 处理文件导入
const handleFileImport = async (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  
  if (!file) return
  
  try {
    const text = await file.text()
    const json = JSON.parse(text)
    
    // 验证是否是有效的 ComfyUI 工作流
    if (!json || typeof json !== 'object') {
      throw new Error('无效的 JSON 文件')
    }

    // 转换工作流格式
    //const convertedWorkflow = convertWorkflowFormat(json)
    
    workflowForm.value.workflow_json = json
    ElMessage.success('工作流导入成功')
  } catch (error) {
    console.error('工作流导入失败:', error)
    ElMessage.error('工作流导入失败，请确保文件格式正确')
  } finally {
    // 清理文件输入，允许重复选择同一文件
    input.value = ''
  }
}

// 转换工作流格式
const convertWorkflowFormat = (original: any) => {
  try {
    const converted = {
      nodes: [],
      links: [],
      inputs: {}
    }

    // 遍历原始节点
    for (const [id, node] of Object.entries(original)) {
      if (typeof node !== 'object' || !node.class_type) continue

      // 创建新节点
      const newNode = {
        id: parseInt(id),
        type: node.class_type,
        position: { x: 0, y: 0 }, // 默认位置
        data: {
          ...node.inputs,
          _meta: node._meta || {}
        }
      }

      converted.nodes.push(newNode)

      // 处理输入参数
      if (node.inputs) {
        for (const [key, value] of Object.entries(node.inputs)) {
          if (Array.isArray(value) && value.length === 2) {
            // 创建连接
            converted.links.push({
              source: value[0],
              target: id,
              sourcePort: value[1],
              targetPort: key
            })
          } else {
            // 添加到全局输入
            converted.inputs[key] = value
          }
        }
      }
    }

    return converted
  } catch (error) {
    console.error('工作流格式转换失败:', error)
    throw new Error('工作流格式转换失败')
  }
}

onMounted(() => {
  if (route.params.id) {
    fetchWorkflowDetail(route.params.id as string)
  }
})
</script>

<style scoped>
.workflow-detail {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.workflow-form {
  max-width: 1200px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.actions {
  display: flex;
  gap: 12px;
}
</style> 